(function ($) {
    var root = daicuo.config.root;
    //附件插件
    var attachment = {
        //上传
        upload: {
            //图片上传
            image: function(e){
                daicuo.upload.init({
                    element: '[data-handler="bootstrap-markdown-cmdUploadImage"]',
                    container: 'markdown-upload-image',//$('.dc-editor').parent().get(0),
                    multiple: true,
                    mimeTypes: 'image/*',
                    onSuccess: function(up, file, xhr){
                        if(file.responseTp.data.water){
                            e.replaceSelection("\n"+'!['+file.responseTp.data.old_name+']('+file.responseTp.data.water+')');
                        }else{
                            e.replaceSelection("\n"+'!['+file.responseTp.data.old_name+']('+file.responseTp.data.url+')');
                        }
                    }
                });
            },
            //积分附件
            file: function(e){
                daicuo.upload.init({
                    element: '#markDownUpload',
                    container: 'markdown-upload-file',
                    multiple: true,
                    params: {score: $('#markDownScore').val()},
                    onInit: function(up){
                        $(document).on('change', '#markDownScore', function(){
                            up.setOption("params", {
                              score : $(this).val()
                            })
                        });
                    },
                    onError: function(up, data){
                        daicuo.bootstrap.dialog(data.msg);
                    },
                    onSuccess: function(up, file){
                        $('.dc-modal .modal-dialog').html(false);
                        $('.dc-modal').modal('hide');
                        //文件名
                        if(file.responseTp.data.score){
                            var fileName = file.responseTp.data.old_name + '（需要'+file.responseTp.data.score+'个积分）';
                        }else{
                            var fileName = file.responseTp.data.old_name;
                        }
                        //插入编辑器
                        if(file.responseTp.data.urlId){
                            e.replaceSelection("\n"+'['+fileName+']('+file.responseTp.data.urlId+')');
                        }else{
                            e.replaceSelection("\n"+'['+fileName+']('+file.responseTp.data.url+')');
                        }
                    }
                });
            }
        },
        //网络文件
        outer: {
            file: function(e){
                $(document).off('submit', '#markDownOuter').on('submit', '#markDownOuter', function() {
                    var self = $(this);
                    daicuo.ajax.post($(this).attr('action'), $(this).serialize(), function($result, $status, $xhr) {
                        if ($result.code == 1) {
                            $('.dc-modal .modal-dialog').html(false);
                            $('.dc-modal').modal('hide');
                            if($result.data.score){
                               e.replaceSelection("\n"+'['+$result.data.name+'（需要'+$result.data.score+'个积分）]('+$result.data.url+')');
                            }else{
                               e.replaceSelection("\n"+'['+$result.data.name+']('+$result.data.url+')');
                            }
                        }else{
                            daicuo.bootstrap.dialog($result.msg);
                        }
                    });
                    return false;
                });
            }
        },
        //列表页
        editor: {
            //监听插入链接
            insert: function(e){
                var selected=e.getSelection();
                $(document).off("click",'[data-toggle="attachment-insert"]').on("click",'[data-toggle="attachment-insert"]',function(){
                    if($(this).parent().data('image')){
                        var html = '!['+$(this).parent().data('title')+']('+$(this).parent().data('image')+')';
                    }else{
                        if($(this).parent().data('score')){
                            var html = '['+$(this).parent().data('title')+'（需要'+$(this).parent().data('score')+'个积分）'+']('+$(this).attr('href')+')';
                        }else{
                            var html = '['+$(this).parent().data('title')+']('+$(this).attr('href')+')';
                        }
                    }
                    //console.log(selected);
                    e.setSelection(selected.start,selected.start);
                    e.replaceSelection(html+"\n");
                    return false;
                });
            },
            //监听删除链接
            delete: function(e){
                $(document).on("click",'[data-toggle="attachment-delete"]',function(){
                    daicuo.ajax.get($(this).attr('href'),function(json,status,xhr){
                        attachment.editor.get($('[data-toggle="attachment-form"]').attr('action'));
                    },function(json,status,html){
                        daicuo.bootstrap.dialog(status);
                    });
                    return false;
                });
            },
            //监听修改链接
            edit: function(e){
                $(document).on("click",'[data-toggle="attachment-edit"]',function(){
                    daicuo.ajax.get($(this).attr('href'),function(html,status,xhr){
                        //动态加载MODAL
                        attachment.editor.modalShow('modal-edit', html);
                        //修改页表单事件
                        attachment.edit.onSubmit();
                        //修改页上传事件
                        attachment.edit.onUpload();
                        //修改页关闭事件
                        attachment.edit.onClose();
                    },function(json,status,html){
                        daicuo.bootstrap.dialog(status);
                    });
                    return false;
                });
            },
            //监听下一页按钮
            next: function(e){
                $(document).on("click",'[data-toggle="attachment-start"]',function(){
                    attachment.editor.get(attachment.editor.urlNext());
                });
            },
            //监听搜索表单
            search: function(e){
                $(document).on('submit','[data-toggle="attachment-form"]', function() {
                    daicuo.ajax.post($(this).attr('action'), $(this).serialize(), function(html, status, xhr) {
                        daicuo.bootstrap.dialogForm(html);
                    });
                    return false;
                });
            },
            //请求附件列表
            get: function(url){
                daicuo.ajax.get(url,function(html,status,xhr){
                    daicuo.bootstrap.dialogForm(html);
                },function(xhr,status,html){
                    daicuo.bootstrap.dialog(status);
                });
            },
            //显示MODAL(modal-edit)
            modalShow: function(element,html){
                $('#'+element).remove();
                $(".dc-modal").after('<div class="modal show" id="'+element+'" style="z-index:100002; display: block;"><div class="modal-dialog modal-sm modal-dialog-centered"><div class="modal-content"><div class="modal-body">' + html + '</div></div></div></div>');
            },
            //隐藏MODAL(#modal-edit)
            modalHide: function(element){
                $('#'+element).remove();
            },
            //当前页URL
            urlReferer: function(){
                return $('[data-toggle="attachment-form"]').attr('action')+'?searchText='+$('[data-toggle="attachment-search"]').val()+'&pageStart='+$('[data-toggle="attachment-start"]').data('referer');
            },
            //下一页URL
            urlNext: function(){
                return $('[data-toggle="attachment-form"]').attr('action')+'?searchText='+$('[data-toggle="attachment-search"]').val()+'&pageStart='+$('[data-toggle="attachment-start"]').data('start');
            }
        },
        //附件修改页
        edit: {
            onSubmit: function(){
                $(document).off('submit','[data-toggle="attachment-edit-form"]').on('submit','[data-toggle="attachment-edit-form"]', function() {
                    daicuo.ajax.post($(this).attr('action'), $(this).serialize(), function(json, status, xhr) {
                        attachment.editor.modalHide('modal-edit');
                        attachment.editor.get(attachment.editor.urlReferer());
                    });
                    return false;
                });
            },
            onUpload: function(){
                daicuo.upload.init({
                    element: '#attachment-edit-upload',
                    container: 'editorEditUpload',
                    multiple: false,
                    params: {
                        id: $('#attachment-edit-id').val(),
                        score: $('#attachment-edit-score').val()
                    },
                    onInit: function(up){
                        $(document).on('change', '#attachment-edit-score', function(){
                            up.setOption("params", {
                               score : $(this).val()
                            })
                        });
                    },
                    onError: function(up, data){
                        attachment.editor.modalShow(data.msg);
                    },
                    onSuccess: function(up, file){
                        attachment.editor.modalHide('modal-edit');
                        attachment.editor.get(attachment.editor.urlReferer());
                    }
                });
            },
            onClose: function(){
                $(document).on("click",'#attachment-edit-close',function(){
                    attachment.editor.modalHide('modal-edit');
                });
            }
        }
    };
    //加载插件
    daicuo.ajax.script([root+'apps/markdown/static/bootstrap-markdown.min.js',root+'apps/markdown/static/hyperdown.min.js'],function(){
        //加载CSS
        daicuo.ajax.css(root+'apps/markdown/static/bootstrap-markdown.css');
        //解析器
        var parser = new HyperDown();
        window.marked = function (text) {
            return parser.makeHtml(text);
        };
        //定义语言
        $.fn.markdown.messages.zh = {
            'Bold': "粗体",
            'Italic': "斜体",
            'Heading': "标题",
            'URL/Link': "链接",
            'Image': "图片",
            'List': "列表",
            'Unordered List': "无序列表",
            'Ordered List': "有序列表",
            'Code': "代码",
            'Quote': "引用",
            'Preview': "预览",
            'strong text': "粗体",
            'emphasized text': "强调",
            'heading text': "标题",
            'enter link description here': "输入链接说明",
            'Insert Hyperlink': "URL地址",
            'enter image description here': "输入图片说明",
            'Insert Image Hyperlink': "图片URL地址",
            'enter image title here': "在这里输入图片标题",
            'list text here': "这里是列表文本",
            'code text here': "这里输入代码",
            'quote here': "这里输入引用文本"
        };
        //调用MarkDown
        $('.dc-editor').markdown({
            resize: 'vertical',
            language: 'zh',
            iconlibrary: 'fa',
            autofocus: false,
            savable: false,
            onShow: function(e){
                //全屏层
                $(".dc-modal").css({'z-index':'100001'});
                //图片上传
                attachment.upload.image(e);
            },
            additionalButtons: [
                [{
                    name: "groupCustom",
                    data: [{
                        name: "cmdUploadImage",
                        toggle: false,
                        title: "上传图片",
                        icon: "fa fa-file-image-o",
                        callback: function (e) {
                            return false;
                        }
                    }, {
                        name: "cmdUploadFile",
                        toggle: false,
                        title: "上传文件",
                        icon: "fa fa-file",
                        callback: function (e) {
                            //$.fn.markdown.element = e;
                            daicuo.ajax.get(root+'markdown/index/upload',function(html,status,xhr){
                                //积分表单
                                daicuo.bootstrap.dialogForm(html);
                                //积分上传
                                attachment.upload.file(e);
                            },function(xhr, status, data){
                                daicuo.bootstrap.dialog(xhr);
                            });
                            return false;
                        }
                    }, {
                        name: "cmdOuterFile",
                        toggle: false,
                        title: "网络文件",
                        icon: "fa fa-file-o",
                        callback: function (e) {
                            daicuo.ajax.get(root+'markdown/index/outer',function(html,status,xhr){
                                //表单界面
                                daicuo.bootstrap.dialogForm(html);
                                //表单事件
                                attachment.outer.file(e);
                            },function(xhr, status, data){
                                daicuo.bootstrap.dialog(xhr);
                            });
                            return false;
                        }
                    }, {
                        name: "cmdAttachment",
                        toggle: false,
                        title: "选择附件",
                        icon: "fa fa-file-text",
                        callback: function (e) {
                            daicuo.ajax.get(root+'attachment/editor/index',function(html,status,xhr){
                                //列表
                                daicuo.bootstrap.dialogForm(html);    
                                //插入
                                attachment.editor.insert(e);
                                //删除
                                attachment.editor.delete(e);
                                //修改
                                attachment.editor.edit(e);
                                //下一页
                                attachment.editor.next(e);
                                //搜索
                                attachment.editor.search(e);
                            },function(xhr, status, data){
                                daicuo.bootstrap.dialog(xhr+'<a class="text-purple text-decoration-none ml-1" href="https://www.daicuo.org/store/attachment" target="_blank">请先安装附件管理插件</a>');
                            });
                            return false;
                        }
                    }]
                }]
            ]
        });
    });
})(jQuery);